<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 产品管理
 *
 * @icon fa fa-cube
 * @remark 管理工厂生产的产品信息
 */
class Product extends Backend
{
    /**
     * Product模型对象
     * @var \app\admin\model\scanwork\Product
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\Product;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['models'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        // 获取工序列表用于工价设置
        $processList = \app\admin\model\scanwork\Process::where('status', 1)->select();
        $this->view->assign('processList', $processList);
        $this->view->assign('processListJson', json_encode($processList));
        
        // 加载自定义字段
        $customFieldsHtml = \app\admin\library\CustomFieldHelper::renderFields('product');
        $this->view->assign('customFieldsHtml', $customFieldsHtml);
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $models = $this->request->post("models/a"); // 型号数据
            $prices = $this->request->post("prices/a"); // 工价数据
            $customFields = $this->request->post("custom_fields/a"); // 自定义字段
            
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    
                    // 保存自定义字段
                    if ($result !== false && $customFields) {
                        \app\admin\library\CustomFieldHelper::saveFieldValues('product', $this->model->id, $customFields);
                    }
                    
                    // 如果产品保存成功且有型号数据，则保存型号和工价
                    if ($result !== false && !empty($models)) {
                        $productId = $this->model->id;
                        
                        foreach ($models as $index => $modelData) {
                            if (!empty($modelData['name'])) {
                                // 保存型号
                                $modelModel = new \app\admin\model\scanwork\ProductModel;
                                $modelParams = [
                                    'product_id' => $productId,
                                    'name' => $modelData['name'],
                                    'model_code' => isset($modelData['model_code']) ? $modelData['model_code'] : '',
                                    'description' => isset($modelData['description']) ? $modelData['description'] : '',
                                    'status' => 1
                                ];
                                $modelResult = $modelModel->save($modelParams);
                                
                                // 如果型号保存成功且有工价数据，则保存工价
                                if ($modelResult !== false && !empty($prices)) {
                                    $modelId = $modelModel->id;
                                    
                                    foreach ($prices as $processId => $priceData) {
                                        // 跳过时间工价字段，只处理计件工价
                                        if (strpos($processId, '_time') !== false) {
                                            continue;
                                        }
                                        
                                        if (isset($priceData[$index]) && $priceData[$index] > 0) {
                                            $priceModel = new \app\admin\model\scanwork\ProcessPrice;
                                            $timePrice = isset($prices[$processId . '_time'][$index]) ? $prices[$processId . '_time'][$index] : 0;
                                            $priceParams = [
                                                'model_id' => $modelId,
                                                'process_id' => $processId,
                                                'price' => $priceData[$index],
                                                'time_price' => $timePrice,
                                                'status' => 1
                                            ];
                                            $priceModel->save($priceParams);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        // 获取工序列表用于工价设置
        $processList = \app\admin\model\scanwork\Process::where('status', 1)->select();
        $this->view->assign('processList', $processList);
        $this->view->assign('processListJson', json_encode($processList));
        
        // 获取产品的型号列表
        $models = \app\admin\model\scanwork\ProductModel::where('product_id', $ids)->select();
        
        // 获取每个型号的工价数据
        $modelsWithPrices = [];
        foreach ($models as $model) {
            $prices = \app\admin\model\scanwork\ProcessPrice::where('model_id', $model->id)->select();
            $priceData = [];
            foreach ($prices as $price) {
                $priceData[$price->process_id] = [
                    'price' => $price->price,
                    'time_price' => $price->time_price
                ];
            }
            
            // 生成该型号的工序HTML
            $processHtml = '';
            foreach ($processList as $process) {
                $price = isset($priceData[$process->id]) ? $priceData[$process->id]['price'] : '';
                $timePrice = isset($priceData[$process->id]) ? $priceData[$process->id]['time_price'] : '';
                
                $processHtml .= '<tr>' .
                    '<td>' . $process->name . '</td>' .
                    '<td><input type="number" class="form-control" name="prices[' . $process->id . '][' . (count($modelsWithPrices)) . ']" placeholder="0.00" step="0.01" min="0" value="' . $price . '"></td>' .
                    '<td><input type="number" class="form-control" name="prices[' . $process->id . '_time][' . (count($modelsWithPrices)) . ']" placeholder="0.00" step="0.01" min="0" value="' . $timePrice . '"></td>' .
                '</tr>';
            }
            
            $modelsWithPrices[] = [
                'model' => $model,
                'prices' => $priceData,
                'process_html' => $processHtml
            ];
        }
        $this->view->assign('models', $modelsWithPrices);
        
        // 生成工序列表的HTML
        $processHtml = '';
        foreach ($processList as $process) {
            $processHtml .= '<tr>' .
                '<td>' . $process->name . '</td>' .
                '<td><input type="number" class="form-control" name="prices[' . $process->id . '][{index}]" placeholder="0.00" step="0.01" min="0" value="{price}"></td>' .
                '<td><input type="number" class="form-control" name="prices[' . $process->id . '_time][{index}]" placeholder="0.00" step="0.01" min="0" value="{time_price}"></td>' .
            '</tr>';
        }
        $this->view->assign('processHtml', $processHtml);
        
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $models = $this->request->post("models/a"); // 型号数据
            $prices = $this->request->post("prices/a"); // 工价数据
            
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    
                    // 如果产品更新成功且有型号数据，则更新型号和工价
                    if ($result !== false && !empty($models)) {
                        $productId = $ids;
                        
                        // 先删除现有的型号和工价
                        $existingModels = \app\admin\model\scanwork\ProductModel::where('product_id', $productId)->select();
                        foreach ($existingModels as $existingModel) {
                            \app\admin\model\scanwork\ProcessPrice::where('model_id', $existingModel->id)->delete();
                            $existingModel->delete();
                        }
                        
                        // 重新创建型号和工价
                        foreach ($models as $index => $modelData) {
                            if (!empty($modelData['name'])) {
                                // 保存型号
                                $modelModel = new \app\admin\model\scanwork\ProductModel;
                                $modelParams = [
                                    'product_id' => $productId,
                                    'name' => $modelData['name'],
                                    'model_code' => isset($modelData['model_code']) ? $modelData['model_code'] : '',
                                    'description' => isset($modelData['description']) ? $modelData['description'] : '',
                                    'status' => 1
                                ];
                                $modelResult = $modelModel->save($modelParams);
                                
                                // 如果型号保存成功且有工价数据，则保存工价
                                if ($modelResult !== false && !empty($prices)) {
                                    $modelId = $modelModel->id;
                                    
                                    foreach ($prices as $processId => $priceData) {
                                        // 跳过时间工价字段，只处理计件工价
                                        if (strpos($processId, '_time') !== false) {
                                            continue;
                                        }
                                        
                                        if (isset($priceData[$index]) && $priceData[$index] > 0) {
                                            $priceModel = new \app\admin\model\scanwork\ProcessPrice;
                                            $timePrice = isset($prices[$processId . '_time'][$index]) ? $prices[$processId . '_time'][$index] : 0;
                                            $priceParams = [
                                                'model_id' => $modelId,
                                                'process_id' => $processId,
                                                'price' => $priceData[$index],
                                                'time_price' => $timePrice,
                                                'status' => 1
                                            ];
                                            $priceModel->save($priceParams);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            } else {
                $this->error(__('Parameter %s can not be empty', ''));
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 检查是否有关联的型号
                    $modelCount = \app\admin\model\scanwork\ProductModel::where('product_id', $item->id)->count();
                    if ($modelCount > 0) {
                        throw new Exception("产品【{$item->name}】下还有{$modelCount}个型号，请先删除相关型号");
                    }
                    $count += $item->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        } else {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
    }
} 